<?php


namespace app\api\controller\v1;

use app\api\model\User as UserModel;
use app\api\model\UserAssetsAuth;
use app\api\model\UserAuthLike;
use app\api\model\UserAuthZan;
use app\api\model\UserEducationAuth;
use app\api\model\UserIncomeAuth;
use app\api\model\UserJobAuth;
use app\api\model\UserPrivacyList;
use app\api\model\UserRealAuth;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;
use think\facade\Request;

use app\api\service\Token as TokenService;
use app\api\model\UserPrivacy as UserPrivacyModel;
use app\api\model\Currency as CurrencyModel;
use app\api\model\System as SystemModel;
use app\api\model\UserAuth as UserAuthModel;

class UserPrivacy
{
    /**
     * 更新隐私设置
     *  1. 判断以及转换好需要添加的数据
     *  2. 修改数据
     *  3. 判断是不是第一次修改，是添加甜茶币
     *  4. 添加修改次数
     */
    public function updateData()
    {
        $data = Request::put();
        $openid = TokenService::getCurrentTokenVar('openid');
        $userPrivacy = UserPrivacyModel::where('openid',$openid)->find();
        $userPrivacyMol = $this->changeData($userPrivacy,$data);
        Db::startTrans();
        try {
            $userPrivacyMol->save();
            // 添加甜茶币
            $this->addCurrency($openid);
            // 添加修改次数
            UserPrivacyModel::where('openid',$openid)->setInc('num',1);
            Db::commit();
            return writeJson(202, [], '修改成功！');
        }
        catch (Exception $ex){
            Db::rollback();
            throw new ParameterException([
                'msg' => [
                    'gr' => '修改失败!'
                ]
            ]);
        }
    }

    /**
     * 添加甜茶币
     */
    private function addCurrency($openid)
    {
        $system = SystemModel::get(1);
        $end_time = time()+7*(24*3600);
        CurrencyModel::create([
            'openid' => $openid,
            'number' => $system['user_privacy_currency'],
            'type' => 1,
            'status' => 3,
            'end_time' => $end_time,
            'min_number' => $system['user_privacy_currency'],
        ]);
    }

    /**
     * 验证以及转换字段
     */
    private function changeData($userPrivacy,$data)
    {
        // 实名认证
        if($data['realAuthType']) {
            $userPrivacy->real_auth_type = 2;
        } else {
            $userPrivacy->real_auth_type = 1;
        }
        // 学历认证
        if($data['educationAuthType']) {
            $userPrivacy->education_auth_type = 2;
        } else {
            $userPrivacy->education_auth_type = 1;
        }
        // 手机认证
        if($data['phoneType']) {
            $userPrivacy->phone_type = 2;
        } else {
            $userPrivacy->phone_type = 1;
        }
        // 姓名
        if($data['nameType']) {
            $userPrivacy->name_type = 2;
        } else {
            $userPrivacy->name_type = 1;
        }
        $userPrivacy->nickname = $data['nickname'];
        // 收入
        if($data['incomeType']){
            $userPrivacy->income_type = 2;
        } else {
            $userPrivacy->income_type = 1;
        }
        // 职业
        if($data['occupationType']){
            $userPrivacy->occupation_type = 2;
        } else {
            $userPrivacy->occupation_type = 1;
        }
        // 身高
        $userPrivacy->height = $data['height'];
        // 学历
        $userPrivacy->education = $data['education'];
        if(count($data['marriage']) > 0) {
            // 婚姻
            $userPrivacy->marriage = implode('-',$data['marriage']);
        }
        if(count($data['constellation']) > 0) {
            // 星座
            $userPrivacy->constellation = implode('-',$data['constellation']);
        }
        // 月收入
        $userPrivacy->wages = $data['wages'];
        // 车
        if($data['car']){
            $userPrivacy->car_type = 2;
        } else {
            $userPrivacy->car_type = 1;
        }
        if(count($data['room']) > 0) {
            // 房
            $userPrivacy->room = implode('-',$data['room']);
        }
        if(count($data['unit']) > 0) {
            // 单位性质
            $userPrivacy->unit = implode('-',$data['unit']);
        }
        // 问题
        $userPrivacy->problem = $data['problem'];
        return $userPrivacy;
    }

    /**
     * 查看联系方式
     */
    public function lookUserAuth($openid,$userInfo)
    {
        $userPrivacyList = UserPrivacyList::where('y_openid',$userInfo['openid'])
            ->where('b_openid',$openid)
            ->find();
        if($openid == $userInfo['openid']) {
            throw new ParameterException([
                'msg' => [
                    'user' => '自己的联系方式不用获取!'
                ]
            ]);
        }
        if($userPrivacyList) {
            if($userPrivacyList['status'] == 1) {
                return [ 'id' => $userPrivacyList['id'], 'type' => 2, 'problem' => $userPrivacyList['problem']];
            } else {
                throw new ParameterException([
                    'msg' => [
                        'user' => '对方联系方式已经获取!'
                    ]
                ]);
            }
        }
        $userPrivacy = UserPrivacyModel::where('openid',$openid)->find();
        $user = UserModel::where('openid',$openid)->find();
        $info = UserAuthModel::with('imgs.img')->where('openid',$openid)->find();
        $info['zan'] = UserAuthZan::where('user_auth_id',$info['id'])
            ->where('openid',$openid)
            ->find();
        $info['like'] = UserAuthLike::where('user_auth_id',$info['id'])
            ->where('openid',$openid)
            ->find();
        $info['zan_num'] = UserAuthZan::where('user_auth_id',$info['id'])->count();
        $info['user'] = UserModel::where('openid',$info['openid'])->find();
        // 实名认证
        $info['auth_real'] = UserRealAuth::where('openid',$info['openid'])
            ->with('justImg,backImg')->find();
        // 手机认证
        $info['auth_phone'] = $user['phone'];
        // 学历认证
        $info['auth_education'] = UserEducationAuth::where('openid',$info['openid'])
            ->find();
        // 工作证明
        $info['auth_job'] = UserJobAuth::where('openid',$info['openid'])
            ->with('jobImg')->find();
        // 收入证明
        $info['auth_income'] = UserIncomeAuth::where('openid',$info['openid'])
            ->with('incomeImg')->find();
        // 资产证明
        $info['auth_assets'] = UserAssetsAuth::where('openid',$info['openid'])
            ->with('assetsImg')->find();
        $userPrivacy['user_auth'] = $info;
        // 实名认证判断
        if($userPrivacy['real_auth_type'] == 2) {
            if(!$userInfo['auth_real']) {
                throw new ParameterException([
                    'msg' => [
                        'user' => '对方设置了实名认证权限,请先进行实名认证!'
                    ]
                ]);
            }
            if($userInfo['auth_real']['status'] != 2) {
                throw new ParameterException([
                    'msg' => [
                        'user' => '对方设置了实名认证权限,实名认证还未通过!'
                    ]
                ]);
            }
        }
        // 学历认证
        if($userPrivacy['education_auth_type'] == 2) {
            if(!$userInfo['auth_education']) {
                throw new ParameterException([
                    'msg' => [
                        'user' => '对方设置了学历认证权限,请先进行学历认证!'
                    ]
                ]);
            }
            if($userInfo['auth_education']['status'] != 2) {
                throw new ParameterException([
                    'msg' => [
                        'user' => '对方设置了学历认证权限,学历认证还未通过!'
                    ]
                ]);
            }
        }
        // 手机认证
        if($userPrivacy['phone_type'] == 2) {
            if(!$userInfo['phone']) {
                throw new ParameterException([
                    'msg' => [
                        'user' => '对方设置了手机认证权限,请先进行手机认证!'
                    ]
                ]);
            }
        }
        // 选择身高
        if($userPrivacy['height']) {
            if(!$userInfo['user_auth']) {
                throw new ParameterException([
                    'msg' => [
                        'user' => '对方设置了身高要求!'
                    ]
                ]);
            }
            if($userInfo['user_auth']['height'] < $userPrivacy['height']) {
                throw new ParameterException([
                    'user' => [
                        'msg' => '对方设置了身高要求!'
                    ]
                ]);
            }
        }
        // 学历
        if($userPrivacy['education']){
            if($userInfo['user_auth']['education'] < $userPrivacy['education']){
                throw new ParameterException([
                    'msg' => [
                        'user' => '对方设置了学历要求!'
                    ]
                ]);
            }
        }
        // 婚姻状态
        if(count($userPrivacy['marriage']) > 0){
            foreach ($userPrivacy['marriage'] as $v) {
                if($userInfo['user_auth']['marriage'] == $v) {
                    throw new ParameterException([
                        'msg' => [
                            'user' => '对方设置了婚姻要求!'
                        ]
                    ]);
                }
            }
        }
        // 星座
        if(count($userPrivacy['constellation']) > 0){
            foreach ($userPrivacy['constellation'] as $v){
                if($userInfo['user_auth']['constellation'] == $v) {
                    throw new ParameterException([
                        'msg' => [
                            'user' => '对方设置了星座要求!'
                        ]
                    ]);
                }
            }
        }
        // 月收入
        if($userPrivacy['wages']) {
            $wages = explode('k',$userPrivacy['wages']);
            $monthly_income = explode('-',$userInfo['user_auth']['monthly_income']);
            $monthly_income_one = explode('k',$monthly_income[0]);
            $monthly_income_two = explode('k',$monthly_income[1]);
            if($monthly_income_one[0] < $wages[0]) {
                throw new ParameterException([
                    'msg' => [
                        'user' => '对方设置了月收入要求!'
                    ]
                ]);
            }
            if($monthly_income_two[0] < $wages[0]) {
                throw new ParameterException([
                    'msg' => [
                        'user' => '对方设置了月收入要求!'
                    ]
                ]);
            }
        }
        // 车
        if($userPrivacy['car_type'] == 2){
            if($userInfo['user_auth']['car'] == 0) {
                throw new ParameterException([
                    'msg' => [
                        'user' => '对方设置了车要求!'
                    ]
                ]);
            }
        }
        // 房
        if(count($userPrivacy['room']) > 0){
            foreach ($userPrivacy['room'] as $v){
                if($userInfo['user_auth']['house'] == $v) {
                    throw new ParameterException([
                        'msg' => [
                            'user' => '对方设置了房要求!'
                        ]
                    ]);
                }
            }
        }
        // 单位
        if(count($userPrivacy['unit']) > 0) {
            foreach ($userPrivacy['unit'] as $v){
                if($userInfo['user_auth']['unit_natures'] == $v) {
                    throw new ParameterException([
                        'msg' => [
                            'user' => '对方设置了单位要求!'
                        ]
                    ]);
                }
            }
        }
        // 回答问题
        if($userPrivacy['problem']){
            $mod = UserPrivacyList::create([
                'y_openid' => $userInfo['openid'],
                'b_openid' => $openid,
                'problem' => $userPrivacy['problem'],
                'msg_json' => json_encode($userPrivacy)
            ]);
            return [ 'id' => $mod->id, 'type' => 2, 'problem' => $userPrivacy['problem']];
        } else {
            $mod = UserPrivacyList::create([
                'y_openid' => $userInfo['openid'],
                'b_openid' => $openid,
                'problem' => $userPrivacy['problem'],
                'status' => 2,
                'msg_json' => json_encode($userPrivacy)
            ]);
            return [ 'id' => $mod->id, 'type' => 1, 'problem' => '' ];
        }
    }

    /**
     * 回答问题操作
     */
    public function questionAnswering($id,$answer)
    {
        UserPrivacyList::where('id',$id)
            ->update([
                'answer' => $answer,
            ]);
        return true;
    }

    /**
     * 修改状态
     */
    public function updateStatus($id)
    {
        UserPrivacyList::where('id',$id)
            ->update([
                'status' => 2,
            ]);
        return true;
    }

    /**
     * 获取发出的邀请，以及收到的邀请
     */
    public function getUserPrivacyList()
    {
        $openid = TokenService::getCurrentTokenVar('openid');
        $one = UserPrivacyList::where('y_openid',$openid)->order('id desc')->select()->each(function (&$item){
            $item['msg_json'] = json_decode($item['msg_json']);
            $item['msg_json']->user_auth->birthday = explode('-',$item['msg_json']->user_auth->birthday);
        })->toArray();
        $two = UserPrivacyList::where('b_openid',$openid)->order('id desc')->select()->each(function (&$item){
            $item['msg_json'] = json_decode($item['msg_json']);
            $user_auth = UserAuthModel::where('openid',$item['y_openid'])->with('imgs.img')->find();
            $user_auth->birthday = explode('-', $user_auth->birthday);
            $item['msg_json']->user_auth = $user_auth;
        })->toArray();
        return [
            'one' => $one,
            'two' => $two,
        ];
    }
}